package com.thkj.service.impl;

import com.github.abel533.entity.Example;
import com.thkj.dao.LoginRecordMapper;
import com.thkj.entity.LogInfo;
import com.thkj.entity.LoginRecord;
import com.thkj.entity.TblSecurityAdmin;
import com.thkj.service.ILoginRecordService;
import com.thkj.util.PropertiesUtils;
import dp.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class LoginRecordServiceImpl implements ILoginRecordService {

    @Autowired
    private LoginRecordMapper loginRecordDao;

    public void save(TblSecurityAdmin rmPerson) {
        LoginRecord loginRecord = new LoginRecord();
        loginRecord.setUserId(rmPerson.getId());
        loginRecord.setUsername(StringUtils.isNotBlank(rmPerson.getRealName()) ? rmPerson.getRealName() : rmPerson.getNickName());
        loginRecord.setVisitTime(DateUtil.getNowAsTimestamp());
        loginRecord.setHeadUrl(rmPerson.getImageUrl());
        loginRecord.setAccount(rmPerson.getLoginName());
        Example example = new Example(LoginRecord.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("account",rmPerson.getLoginName());
        List<LoginRecord> select = loginRecordDao.selectByExample(example);
        if (select != null && select.size() > 0) {
            LoginRecord loginRecord1 = select.get(0);
            loginRecord.setVisitTime(DateUtil.getNowAsTimestamp());
            loginRecordDao.updateByPrimaryKey(loginRecord1);
        } else {
            loginRecordDao.insert(loginRecord);
        }
    }

    @Override
    public List<LoginRecord> queryByRecen() {

        Example example = new Example(LoginRecord.class);
        example.setOrderByClause("visit_time DESC");

        List<LoginRecord> records = loginRecordDao.selectByExample(example);
        return records.stream().map(loginRecord -> {
            if (StringUtils.isBlank(loginRecord.getHeadUrl())) {
                loginRecord.setHeadUrl(PropertiesUtils.getProperty("sys.constants.manage.head.default.url"));
            }
            return loginRecord;
        }).collect(Collectors.toList());
    }
}
